package learn.stack;

import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * @author baoshi
 */
public class PolandNation {
    public static void main(String[] args) {
//        //定义一个逆波兰表达式 （3+4）*5-6
//        String suffixExtension = "3 4 + 5 * 6 -";
//
//        //将 suffixExtension 转换为集合 ArrayList
//        List<String> list = getListString(suffixExtension);
//        //将ArrayList 传递给一个方法 配合栈（遍历ArrayList） 完成计算
//        System.out.println(calculate(list));
        String expression = "1+((2+3)*4)-5";
        List<String> list = getPolandNations(expression);
        int calculate = calculate(list);
        System.out.println(calculate);
    }

    @org.jetbrains.annotations.NotNull
    @org.jetbrains.annotations.Contract("_ -> new")
    public static List<String> getListString(@NotNull String suffixExtension) {
        String[] split = suffixExtension.split(" ");
        return new ArrayList<>(Arrays.asList(split));
    }

    public static int calculate(List<String> list) {
        Stack<String> stack = new Stack<>();

        for (String item : list) {
            if (item.matches("\\d+")) {//匹配多位数
                stack.push(item);
            } else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;
                switch (item) {
                    case "+":
                        res = num2 + num1;
                        break;
                    case "-":
                        res = num2 - num1;
                        break;
                    case "*":
                        res = num2 * num1;
                        break;
                    case "/":
                        res = num2 / num1;
                        break;
                    default:
                        throw new RuntimeException("运算符不合法: " + item);
                }
                stack.push(String.valueOf(res));
            }
        }
        return Integer.parseInt(stack.pop());
    }

    /**
     * 将中缀表达式转换为后缀表达式
     * @param expression 中缀表达式
     * @return 后缀表达式
     */
    public static List<String> getPolandNations(String expression) {
        //使用索引遍历复杂，将expression转换为ArrayList
        List<String> list = toInfixExpressionList(expression);
        //创建操作符栈s1 与 中间结果栈 s2
        Stack<String> s1 = new Stack<>();
        Stack<String> s2 = new Stack<>();
        for (String item : list) {
            if (item.matches("\\d+")) {//数字直接入s2
                s2.push(item);
            } else if (item.equals("(")) {//左括号直接入栈
                s1.push(item);
            } else if (item.equals(")")) {
                //右括号依次弹出s1元素，压入s2，直至遇到左括号
                while (!s1.peek().equals("(")) {
                    s2.push(s1.pop());
                }
                s1.pop();//弹出"("
            } else {
                while (s1.size() != 0 && Operation.getValue(item) <= Operation.getValue(s1.peek())) {
                    //s1不为空，当前运算符的优先级<=栈顶的优先级，将s1的元素弹出，压入s2
                    s2.push(s1.pop());
                }
                s1.push(item);
            }
        }
        //将s1中剩余的元素全部转换到s2
        while (s1.size() != 0) {
            s2.push(s1.pop());
        }
        ArrayList<String> result = new ArrayList<>();
        while (s2.size() != 0) {
            result.add(s2.pop());
        }
        Collections.reverse(result);
        return result;
    }
    /**
     * 将expression转换为ArrayList
     *
     * @param expression 中缀表达式
     * @return 中缀表达式ArrayList
     */
    public static List<String> toInfixExpressionList(String expression) {
        ArrayList<String> list = new ArrayList<>();
        int index = 0;//遍历字符串的指针
        String num = ""; //多位数的暂存区
        char ch = ' ';//遍历取出的单个字符
        do {
            ch = expression.charAt(index);
            if (ch < 48 || ch > 57) {//不是数字
                list.add(String.valueOf(ch));
                index++;
            } else {
                num = "";
                while (expression.length() > index && (expression.charAt(index) >= 48 && expression.charAt(index) <= 57)) {
                    //没有遍历结束，并且为数字
                    num += expression.charAt(index);//拼接多位数
                    index++;
                }
                list.add(num);
            }

        } while (expression.length() > index);
        return list;
    }
}

/**
 * 返回一个字符的优先级
 */
class Operation {
    private static int ADD = 1;
    private static int SUB = 1;
    private static int MUL = 2;
    private static int DIV = 2;

    public static  int getValue(String operation) {
        int result = 0;
        switch (operation) {
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
                break;
            case "*":
                result = MUL;
                break;
            case "/":
                result = DIV;
                break;
            case "(":
            case ")":
                result = -10000000;
                break;
            default:
                throw new RuntimeException("运算符不合法：" + operation);
        }
        return result;
    }
}
